package fun.codedesign.jdk.lang.oop.basic.ball;

import javax.swing.*;
import java.awt.*;

public class BallPanel extends JPanel {

    Ball[] balls;

    public BallPanel() {
        balls = new Ball[200];
        for (int i = 0; i < balls.length; i++) {
            Color color = new Color((int) (Math.random() * 256), (int) (Math.random() * 256), (int) (Math.random() * 256));
            int x = (int) (Math.random() * 900);
            int y = (int) (Math.random() * 700);
            int speed = (int) (Math.random() * 5) + 1;
            int r = (int) (Math.random() * 20 + 15);
            int direction = (int) (Math.random() * 4);
            balls[i] = new Ball(x, y, r, speed, direction, color, this);
            System.out.println(i);
        }
    }

    public void paint(Graphics g) {

        super.paint(g);
        this.setBackground(Color.white);

        for (Ball ball : balls) {
            ball.draw(g);
        }
    }

    public void startRun() {
        Thread t = new Thread() {
            public void run() {

                while (true) {
                    for (Ball ball : balls) {
                        ball.move();
                    }
                    repaint();
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        t.start();
    }
}
